// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.server.service;

import java.util.List;
import net.taviscaron.drivenotes.server.model.dao.NoteDAO;
import net.taviscaron.drivenotes.server.model.validators.Validator;
import net.taviscaron.drivenotes.server.util.EntityUtils;
import net.taviscaron.drivenotes.shared.exceptions.InvalidEntityException;
import net.taviscaron.drivenotes.shared.model.entity.Note;
import net.taviscaron.drivenotes.shared.model.entity.User;
import net.taviscaron.drivenotes.shared.service.NoteService;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

/**
 * Note service impl
 * @author Andrei Senchuk
 */
public class NoteServiceImpl implements NoteService {
    private Validator<Note> noteValidator;
    private NoteDAO noteDAO;

    @Required
    public void setNoteDAO(NoteDAO noteDAO) {
        this.noteDAO = noteDAO;
    }

    @Required
    public void setNoteValidator(Validator<Note> noteValidator) {
        this.noteValidator = noteValidator;
    }
    
    @Transactional
    public List<Note> findNotesByUser(User user) {
        List<Note> notes = noteDAO.findByOwnerId(user.getId());
        for(int i = 0; i < notes.size(); i++) {
            notes.set(i, EntityUtils.createNoteValueObject(notes.get(i)));
        }
        return notes;
    }

    @Transactional
    public Note findNote(Long id, User author) {
        Note note = noteDAO.findByOwnerAndId(author, id);
        return EntityUtils.createNoteValueObject(note);
    }

    @Transactional
    public void saveNote(Note note) throws InvalidEntityException {
        noteValidator.validate(note);
        noteDAO.save(note);
    }

    @Transactional
    public void removeNoteById(Long id) {
        Note note = noteDAO.findById(id);
        noteDAO.remove(note);
    }
}
